<?php

namespace App\Util;

class CodeStyleUtil
{
    const STYLE_CAMEL_CASE = 'camelCase'; // 小驼峰
    const STYLE_SNAKE_CASE = 'snake_case'; // 蛇形

    public static $ins;

    /**
     * 单例模式
     */
    public static function getInstance()
    {
        if (self::$ins instanceof self) {
            return self::$ins;
        }
        self::$ins = new self();
        return self::$ins;
    }

    /**
     * 转小驼峰
     * @param $string
     *
     * @return string
     * @author Chris Yu <chrisyu@crabapple.top> 2023/3/28
     */
    public function toCamelCase($str) {
        $str = ucwords(str_replace(['-', '_'], ' ', $str));
        return lcfirst(str_replace(' ', '', $str));
    }

    /**
     * 转蛇形写法
     * @param $string
     *
     * @return string
     * @author Chris Yu <chrisyu@crabapple.top> 2023/3/28
     */
    public function toSnakeCase($str) {
        return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $str));
    }

    /**
     * 转风格
     * @param $str
     * @param $style
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2023/3/28
     */
    public function to($str, $style)
    {
        if ($style === self::STYLE_CAMEL_CASE) {
            return $this->toCamelCase($str);
        }
        elseif ($style === self::STYLE_SNAKE_CASE) {
            return $this->toSnakeCase($str);
        }
        else {
            return $str;
        }
    }

    /**
     * 数组转风格
     * @param $input
     * @param $style
     *
     * @author Chris Yu <chrisyu@crabapple.top> 2023/3/28
     */
    public function arrayTo($input, $style)
    {
        $output = [];
        foreach ($input as $key => $item) {
            $output[$this->to($key, $style)] = $item;
        }
        return $output;
    }
}
